import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * 
 * @author "Cunxin Jia"
 *
 */

public class VarFactory {
	private static VarFactory instance = null;
	private Map<Set<Term>,String> varMap;
	public VarFactory() {
		varMap = new HashMap<Set<Term>,String>();
 	}	
	public static VarFactory getInstance() {
		if(instance == null) 
			instance = new VarFactory();
		return instance;
	}
	public String getLGGTerm(Term term1, Term term2) {
		Set<Term> termSet = new HashSet<Term> ();
		termSet.add(term1);
		termSet.add(term2);
		
		String newVar = getExistedVar(termSet);
		if(newVar == null) {
			int newVarIndex = varMap.size();
			newVar = generateNewVar(newVarIndex);
			varMap.put(termSet, newVar);
		}
		return newVar;
	}
	
	private String getExistedVar(Set<Term> termSet) {
		Set<Set<Term>> keySet = varMap.keySet();
		Iterator<Set<Term>> iter = keySet.iterator();
		while(iter.hasNext()) {
			Set<Term> curSet = iter.next();
			if(curSet.containsAll(termSet)){
				return varMap.get(curSet);
			}
		}
		return null;
	}
	
	private String generateNewVar(int index) {
		String varString;
		if(index < 26) {
			char varChar = (char) ('A' + index);
			varString = String.valueOf(varChar);
		}
		else {
			varString = (char)('A' + index/26) + "" + (index % 26);
		}
		return varString;
		
	}
	
	public void printAll() {
		Set<Set<Term>> terms = varMap.keySet();
		Iterator<Set<Term>> iter = terms.iterator();
		while(iter.hasNext()) {
			Set<Term> set = iter.next();
			String varString = varMap.get(set);
			System.out.print(varString + ": ");
			Iterator<Term> innerIter = set.iterator();
			while(innerIter.hasNext()) {
				Term term = innerIter.next();
				System.out.print(term.getVar() + " ");
			}
			System.out.println();
		}
	}
}
